package com.example.security;

import cn.hutool.json.JSONUtil;
import com.example.common.annotation.LoginLogAnno;
import com.example.common.result.Result;
import com.example.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
//登录成功处理器
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    JwtUtil jwtUtil;

    @LoginLogAnno(operateType = "用户登录")
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //设置返回类型和字符编码
        response.setContentType("application/json;charset=UTF-8");
        //定义一个response输出流
        ServletOutputStream outputStream = response.getOutputStream();

        //生成jwt，放到响应头
        String jwt = jwtUtil.generateToken(authentication.getName());
        response.setHeader(jwtUtil.getHeader(), jwt);

        //将jwt封装成Result
        Result result = Result.ok().message("登录成功");

        //将result写入输出流中
        outputStream.write(JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8));
        //刷新此输出流并强制写出所有缓冲的输出字节
        outputStream.flush();
        //将输出流关闭
        outputStream.close();
    }
}
